// import request from './request'
import * as qiniu from 'qiniu-js'

// var tokenUrl = process.env.VUE_APP_DOMAIN + '/dmz/qiniu/token' //获取七牛token的地址


class Qiniu {

    // static init(tokenUrl) {
    //     if (this.token) return
    //     request.get(tokenUrl).then(res => {
    //         this.token = res.data
    //     })
    // }

    /**
     * 上传base64的图片到七牛 返回文件名
     * @param base64File
     * @returns {Promise<any>}
     */
    static uploadBase64Img(base64File) {
        return new Promise(resolve => {
            let pic = base64File.replace('"', '').split(',')[1]
            let url = "http://upload.qiniup.com/putb64/-1"; //非华东空间需要根据注意事项 1 修改上传域名 -1表示不传文件大小
            let xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    let result = JSON.parse(xhr.responseText)
                    resolve(result.key)
                }
            }
            xhr.open("POST", url, true);
            xhr.setRequestHeader("Content-Type", "application/octet-stream");
            xhr.setRequestHeader("Authorization", 'UpToken ' + this.token);
            xhr.send(pic);
        })
    }

    static createKey(name) {
        return new Date().valueOf() + name
    }


    /**
     * 上传文件
     * @param file
     * @param observer 返回回调 {next:fun,success:fun}
     */
    static uploadImg(token ,file, observer) {
        let config = {
            useCdnDomain: true
        };
        let observable = qiniu.upload(file, this.createKey(file.name), token, null, config)
        observable.subscribe(observer)
    }


}

export default Qiniu
